<template>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    @confirm="onSubmit"
    :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }"
    width="80%"
    top="5%"
    v-if="editOpen"
  >
   <div style="height: 65vh;">
     <t-form ref="form" labelAlign="top" :data="formData" labelWidth="100px" :rules="rules">
       <t-row style="margin-bottom: 12px">
         <!--        <t-col :span="12">-->
         <!--          <t-form-item label="导入之前的指标体系">-->
         <!--            <t-select-->
         <!--              filterable-->
         <!--              clearable-->
         <!--              placeholder="体系名称"-->
         <!--              :options="options"-->
         <!--              @change="onChange"-->
         <!--              style="width: 390px"-->
         <!--            />-->
         <!--          </t-form-item>-->
         <!--        </t-col>-->
         <t-col :span="6">
           <t-form-item label="体系名称" name="name">
             <t-input clearable style="width: 390px"  v-model="formData.name" :maxLength="100" placeholder="请输入体系名称"></t-input>
             <t-popup v-if="options.length>0  && !objId">
               <t-button variant="text" class="t-button-link">
                 <t-icon name="add" slot="icon"/>
                 导入历史
               </t-button>
               <template #content>
                 <t-select
                   filterable
                   clearable
                   placeholder="体系名称"
                   :options="options"
                   @change="onChange"
                 />
               </template>
             </t-popup>

           </t-form-item>
         </t-col>
         <t-col :span="6">
           <t-form-item label="总分值" name="score">
             {{formData.score}}
<!--             <t-input-number clearable v-model="formData.score" :min="0" placeholder="请输入"></t-input-number>-->
           </t-form-item>
         </t-col>
       </t-row>
       <t-form-item label="说明" name="note">
         <t-textarea :autosize="{minRows: 5}"
                     v-model="formData.note"  placeholder="请输入内容"/>
       </t-form-item>
       <t-form-item label="指标列表" name="reviewItems">
         <div>
           <t-table
             rowKey="id"
             :data="formData.reviewItems"
             :columns="columns"
             bordered
             hover
             :selected-row-keys="selectedRowKeys"
             @select-change="(val)=>{selectedRowKeys=val}"
           >
             <template #id="{rowIndex}">
               {{ rowIndex + 1 }}
             </template>
             <template #name="{row}">
               <t-input clearable v-model="row.name"></t-input>
             </template>
             <template #note="{row}">
               <t-textarea :autosize="{minRows: 3}"
                           v-model="row.note" placeholder="请输入内容"/>
             </template>
             <template #score="{row}">
               <t-input-number clearable :min="0" v-model="row.score"></t-input-number>
             </template>
           </t-table>
           <div style="margin-top: 10px" class="btn-group-inline">
             <t-button @click="addData">新增</t-button>
             <t-button @click="upData">上移</t-button>
             <t-button @click="downData">下移</t-button>
             <t-button @click="delData">删除</t-button>
           </div>
         </div>
       </t-form-item>
     </t-form>
   </div>
  </t-dialog>
  <div v-else>
    <t-dialog
      :header="header"
      :visible.sync="visible"
      :onClose="closeDialog"
      :closeOnOverlayClick="false"
      :confirmBtn="null"
      width="60%"
      top="5%"
      v-if="isDialog"
    >
      <div style="height: 65vh">
        <t-form ref="form" labelAlign="top" :colon="true" :data="formData" labelWidth="100px">
          <t-row style="margin-bottom: 12px">
            <t-col :span="6">
              <t-form-item label="体系名称" name="name">
                {{ formData.name }}
              </t-form-item>
            </t-col>
            <t-col :span="6">
              <t-form-item label="总分值" name="score">
                {{ formData.score }}
              </t-form-item>
            </t-col>
          </t-row>
          <t-form-item label="说明" name="note">
            {{ formData.note }}
          </t-form-item>
          <t-form-item label="指标列表" name="reviewItems">
            <div>
              <t-table
                rowKey="id"
                :data="formData.reviewItems"
                :columns="columns2"
                bordered
                hover
                :selected-row-keys="selectedRowKeys"
                @select-change="(val)=>{selectedRowKeys=val}"
              >
                <template #id="{rowIndex}">
                  {{ rowIndex + 1 }}
                </template>
              </t-table>
            </div>
          </t-form-item>
        </t-form>
      </div>
    </t-dialog>
    <template v-else>
      <t-form ref="form" labelAlign="top" :colon="true" :data="formData" labelWidth="100px">
        <t-row style="margin-bottom: 12px">
          <t-col :span="6">
            <t-form-item label="体系名称" name="name">
              {{ formData.name }}
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item label="总分值" name="score">
              {{ formData.score }}
            </t-form-item>
          </t-col>
        </t-row>
        <t-form-item label="说明" name="note">
          {{ formData.note }}
        </t-form-item>
        <t-form-item label="指标列表" name="reviewItems">
          <div>
            <t-table
              rowKey="id"
              :data="formData.reviewItems"
              :columns="columns2"
              bordered
              hover
              :selected-row-keys="selectedRowKeys"
              @select-change="(val)=>{selectedRowKeys=val}"
            >
              <template #id="{rowIndex}">
                {{ rowIndex + 1 }}
              </template>
            </t-table>
          </div>
        </t-form-item>
      </t-form>
    </template>
  </div>

</template>

<script>

export default {
  name: "add-edit-review-standard",
  components: {},
  props: {
    header: String,
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
    isDialog: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      options: [],
      visible: true,
      loading: false,
      selectedRowKeys: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 100
        },
        {
          colKey: "name",
          title: "指标名称",
          align: "center",
        },
        {
          colKey: "note",
          title: "指标说明",
          align: "center",
        },
        {
          colKey: "score",
          title: "分值",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: "id",
          title: "序号",
          align: "center",
          width: 100
        },
        {
          colKey: "name",
          title: "指标名称",
          align: "center",
        },
        {
          colKey: "note",
          title: "指标说明",
          align: "center",
        },
        {
          colKey: "score",
          title: "分值",
          align: "center",
        },
      ],
      formData: {
        score: 100,
        name: "",
        reviewItems: [],
        note: '',
      },
      rules: {
        name: [{required: true, message: "体系名称不能为空"}],
        note: [{required: true, message: "说明不能为空"}],
        score: [{required: true, validator: (val) => val > 0, message: "总分值需要大于0", type: "error"}],
        reviewItems: [{required: true, validator: (val) => val.length > 0, message: "指标列表不能为空", type: "error"}],
      }
    }
  },
  watch: {
    objId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getObj(val);
        }
      }
    }
  },
  created() {
    this.$api.kjxm.review.indexList({
      pageNum: 1,
      pageSize: 10000
    }).then(
      (res) => {
        this.options = res.rows.map(val => ({value: val.id, label: val.name}));
      }).catch((e) => {
      this.$message.error(e.toString());
    });
  },
  methods: {
    onInputChange(val){
      this.formData.name = val;
    },
    onChange(val) {
      // 通过val 查询值
      if(typeof(val) === 'number'){
        this.$api.kjxm.review.indexGet(val).then((response) => {
          // his.$set(obj,key,value)
          this.formData = response.data;
        });
      }
    },
    createOptions(value) {
      this.options.push({
        value,
        label: value,
      });
    },
    getObj(id) {
      this.$api.kjxm.review.indexGet(id).then((response) => {
        this.formData = response.data;
      });
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          //  验证标准列表
          const isValidate = this.formData.reviewItems.every((val, index) => {
            const tag = "指标列表";
            if (val.name === "") {
              this.$message.error(`${tag}：第${index + 1}条"指标名称"不能为空`);
              return false;
            }
            if (val.score <= 0) {
              this.$message.error(`${tag}：第${index + 1}条"分数"需要大于0`);
              return false;
            }
            return true;
          });
          if (!isValidate) {
            return false
          }
          let totalScore = 0;
          this.formData.reviewItems.forEach((val, index) => {
            this.formData.reviewItems[index].sort = index + 1;
            totalScore += val.score;
          });
          if (totalScore !== this.formData.score) {
            this.$message.error(`指标列表分值总额"${totalScore}"不等于体系总分值"${this.formData.score}"`);
            return false;
          }
          this.loading = true;
          if (this.objId !== 0) {
            this.$api.kjxm.review.indexUpdate(this.formData).then((response) => {
              this.$message.success("修改成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            this.$api.kjxm.review.indexAdd(this.formData).then((response) => {
              this.$message.success("新增成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
    addData() {
      this.formData.reviewItems.push({id: Date.parse(new Date()), name: "", score: null, note: ""});
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.formData.reviewItems[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.formData.reviewItems.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.formData.reviewItems, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.formData.reviewItems[this.formData.reviewItems.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.formData.reviewItems.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.formData.reviewItems, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.formData.reviewItems.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.formData.reviewItems.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style scoped>
</style>
